<template>
    <div class="room-manage">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="iconfont icon-fangjian"></i>&nbsp;房间管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-input v-model="query.oldmanName" placeholder="老人名称" class="handle-input mr10" @change="handleSearch"></el-input>
                <el-select v-model="query.roomType" placeholder="请选择房型" class="handle-input mr10" clearable @change="handleSearch">
                    <el-option
                            v-for="item in roomTypeList"
                            :key="item"
                            :label="item"
                            :value="item">
                    </el-option>
                </el-select>
                <el-select v-model="query.roomStatus" placeholder="请选择房间状态" class="handle-input mr10" clearable @change="handleSearch">
                    <el-option
                            v-for="item in roomStatusList"
                            :key="item"
                            :label="item"
                            :value="item">
                    </el-option>
                </el-select>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
                <el-button
                        type="primary"
                        icon="el-icon-delete"
                        class="handle-del mr10"
                        @click="delAllSelection"
                >批量删除</el-button>
            </div>
            <el-table
                    :data="tableData"
                    border
                    class="table"
                    ref="multipleTable"
                    :height="tableHeight"
                    header-cell-class-name="table-header"
                    @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" align="center"></el-table-column>
                <!--<el-table-column type="index" label="序号" width="55" align="center" :index='(index)=>{return (index+1) + (query.currentPage-1)*query.pageSize }'></el-table-column>-->
                <el-table-column prop="id" label="房间编号" align="center" width="80px"></el-table-column>
                <el-table-column prop="dayLeft" label="剩余天数" align="center" sortable min-width="80px"></el-table-column>
                <el-table-column label="单价" align="center" sortable min-width="80px">
                    <template slot-scope="scope">
                        <div>￥{{ scope.row.unitPrice }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="房型" align="center" sortable min-width="80px">
                    <template slot-scope="scope">
                        <div><i class="iconfont icon-huxing" style="font-size: 13px;color: #409eff"></i>&nbsp;{{ scope.row.roomType }}</div>
                    </template>
                </el-table-column>
                <el-table-column prop="roomArea" label="面积" align="center" sortable min-width="80px">
                    <template slot-scope="scope">
                        <div>{{ scope.row.unitPrice }} m²</div>
                    </template>
                </el-table-column>
                <el-table-column prop="roomDevice" label="房间设施" align="center" min-width="200px"></el-table-column>
                <el-table-column prop="roomStatus" label="房间状态" align="center" min-width="80px">
                    <template slot-scope="scope">
                        <div style="color: #409eff" v-if="scope.row.roomStatus == '已租用'">
                            <i class="iconfont icon-chuangweizuyong" style="font-size: 13px;color: #409eff"></i>
                            {{ scope.row.roomStatus }}
                        </div>
                        <div style="color: #E6A23C" v-else>
                            <i class="iconfont icon-xianzhichuli" style="font-size: 13px;color: #E6A23C"></i>
                            {{ scope.row.roomStatus }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="租住人" align="center" min-width="80px">
                    <template slot-scope="scope" v-if="scope.row.oldmanName">
                        <div><i class="iconfont icon-laoren" style="font-size: 15px;"></i>{{ scope.row.oldmanName }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150" align="center">
                    <template slot-scope="scope">
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="handleEdit(scope.$index, scope.row)"
                        >修改</el-button>
                        <el-button
                                type="text"
                                icon="el-icon-delete"
                                @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                        background
                        layout="-> ,sizes , prev, pager, next"
                        :current-page="query.currentPage"
                        :page-size="query.pageSize"
                        :total="pageTotal"
                        @current-change="handlePageChange"
                        @size-change="handleSizeChange"
                        :page-sizes="[10, 20, 50, 100]"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog :title="dialogTitle" v-dialogDrag :visible.sync="editVisible" width="555px">
            <el-form ref="form" :model="form" label-position="left" label-width="90px" :rules="rules">
                <el-form-item label="房间编号" v-if="dialogTitle!='新增房间信息'" prop="id">
                    <el-input v-model="form.id" disabled></el-input>
                </el-form-item>
                <el-form-item label="房型" prop="roomType">
                    <el-radio v-model="form.roomType" label="大户">大户 <i class="iconfont icon-kongtiao"></i></el-radio>
                    <el-radio v-model="form.roomType" label="中户">中户&nbsp;<i class="iconfont icon-chuang"></i></el-radio>
                    <el-radio v-model="form.roomType" label="小户">小户&nbsp;<i class="iconfont icon-zhuozicopy"></i></el-radio>
                </el-form-item>
                <el-form-item label="面积" prop="roomArea">
                    <el-input v-model="form.roomArea">
                        <template slot="append">m²</template>
                    </el-input>
                </el-form-item>
                <el-form-item class="group-divide" label="房间设施" prop="roomDevice">
                    <el-checkbox-group v-model="form.roomDevice">
                        <el-checkbox label="空调">空调&nbsp;<i class="iconfont icon-kongtiao"></i></el-checkbox>>
                        <el-checkbox label="床">床&nbsp;<i class="iconfont icon-chuang"></i></el-checkbox>
                        <el-checkbox label="桌子">桌子&nbsp;<i class="iconfont icon-zhuozicopy"></i></el-checkbox>
                        <el-checkbox label="椅子">椅子&nbsp;<i class="iconfont icon-yizi"></i></el-checkbox>
                        <el-checkbox label="衣柜">衣柜&nbsp;<i class="iconfont icon-yigui"></i></el-checkbox>
                        <el-checkbox label="冰箱">冰箱&nbsp;<i class="iconfont icon-bingxiang"></i></el-checkbox>
                        <el-checkbox label="微波炉">微波炉&nbsp;<i class="iconfont icon-weibolu"></i></el-checkbox>
                        <el-checkbox label="热水器">热水器&nbsp;<i class="iconfont icon-reshuiqi"></i></el-checkbox>
                        <el-checkbox label="洗衣机">洗衣机&nbsp;<i class="iconfont icon-xiyiji"></i></el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="房间单价" prop="unitPrice">
                    <el-input v-model="form.unitPrice">
                        <template slot="append">元</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="出租状态" prop="roomStatus">
                    <el-radio v-model="form.roomStatus" label="已租用" :disabled="dialogTitle=='新增房间信息'">已租用</el-radio>
                    <el-radio v-model="form.roomStatus" label="已闲置">已闲置</el-radio>
                </el-form-item>

                <div class="group-title" v-if="form.roomStatus == '已租用'">
                    <span>租住人信息</span>
                </div>
                <el-form-item label="老人姓名" v-if="form.roomStatus == '已租用'" prop="oldmanId">
                    <el-select v-model="form.oldmanId" filterable placeholder="请选择">
                        <el-option
                                v-for="item in oldmanList"
                                :key="item.id"
                                :label="item.oldmanName"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="房间剩余天数" label-width="120px" v-if="form.roomStatus == '已租用'" prop="dayLeft">
                    <el-col :span="11">
                        <el-input v-model="form.dayLeft" disabled></el-input>
                    </el-col>
                    <el-col class="line" :span="2" style="text-align: center">+</el-col>
                    <el-col :span="11">
                        <el-input-number v-model="form.addDay" controls-position="right" style="width: 100%"></el-input-number>
                    </el-col>
                </el-form-item>

            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="saveEdit">确 定</el-button>
                <el-button @click="editVisible = false">取 消</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        data() {

            var oldmanId = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('租住人不能为空'));
                } else {
                    callback();
                }
            };

            var dayLeft = (rule, value, callback) => {
                if ( !this.form.dayLeft && !this.form.addDay ) {
                    return callback(new Error('租住时间不能为空'));
                } else {
                    callback();
                }
            };

            return {
                query               : {
                    oldmanName : '',
                    roomType : '',
                    roomStatus : '',
                    currentPage : 1,
                    pageSize : 10
                },
                tableData           : [],
                multipleSelection   : [],
                delList             : [],
                editVisible         : false,
                pageTotal           : 0,
                form                : {
                    roomType : '大户',
                    roomArea : '',
                    roomDevice : [],
                    unitPrice : '',
                    roomStatus : '已闲置',
                    oldmanId : '',
                    dayLeft : 0,
                    addDay : 0,
                },
                tableHeight         : document.documentElement.clientHeight-350,    // 表格高度
                dialogTitle         : '',
                rules               : {
                    oldmanId : [{ required: true, validator: oldmanId, trigger: 'blur' }],
                    dayLeft  : [{ required: true, validator: dayLeft, trigger: 'blur' }],
                },
                oldmanList          : [],
                roomTypeList        : ['大户','中户','小户'],
                roomStatusList      : ['已租用','已闲置','已到期'],
            };
        },
        watch :{
            /**
             * 监听新增/编辑 弹窗关闭 重置表单数据
             * @param   nv 新值
             * @param   ov 之前值
             */
            editVisible(nv,ov){
                if(!nv){
                    // 重置表单数据
                    this.$refs.form.resetFields();

                    /**
                     * 由于from点id未被表单绑定，当表单清空时，id不能及时清空，需要手动清除
                     */
                    if(this.form.id){
                        delete this.form.id;
                    };
                }
            },
        },
        methods: {
            /**
             * 获取表格数据
             */
            getData() {
                this.$api.getRooms( this.query ).then((res)=>{
                    this.tableData = res.data;
                    this.pageTotal = res.total;
                });
            },

            /**
             * 触发搜索按钮
             */
            handleSearch() {
                this.$set(this.query, 'currentPage', 1);
                this.getData();
            },

            /**
             * 删除操作
             */
            handleDelete(index, row) {
                // 二次确认删除
                this.$confirm(`确定要删除 ${row.id} 号房间的信息吗？`, '提示', {
                    type: 'warning',
                    center: true
                }).then(() => {
                    this.$api.deleteRoom([
                        row.id
                    ]).then((res)=>{
                        this.$message.success('删除成功');
                        this.getData();
                    })
                }).catch(() => {});
            },

            /**
             * 多选操作
             */
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },

            /**
             * 删除选中数据
             */
            delAllSelection() {
                let length = this.multipleSelection.length,
                    arr    = [];

                // 没有选择项直接结束
                if (!length) return;

                for (let i = 0; i < length; i++) {
                    arr.push(this.multipleSelection[i].id);
                };

                this.$api.deleteRoom(arr).then((res)=>{
                    this.$message.success('删除成功');
                    this.multipleSelection = [];
                    this.getData();
                })
            },

            /**
             * 新增操作
             */
            handleAdd(){
                this.dialogTitle = "新增房间信息";
                this.editVisible = true;
            },

            /**
             * 编辑操作
             */
            handleEdit(index, row) {
                this.dialogTitle = "编辑房间信息";
                this.editVisible = true;

                var obj = JSON.parse(JSON.stringify(row));
                obj.roomDevice = obj.roomDevice == "" ? [] : obj.roomDevice.split('、');
                obj.addDay = 0;
                // this.$nextTick()将赋值操作放到dom渲染结束之后
                this.$nextTick(() => {
                    this.form = obj;
                })
            },

            /**
             * 保存编辑
             */
            saveEdit() {

                this.$refs.form.validate(valid => {
                    if (!valid) {
                        return this.$message({
                            message: '请核对填写信息',
                            type: 'error'
                        });
                    };

                    var obj = JSON.parse(JSON.stringify(this.form));

                    obj.roomArea = obj.roomArea * 1;
                    obj.unitPrice = obj.unitPrice * 1;
                    obj.dayLeft = obj.dayLeft * 1 + obj.addDay * 1;

                    obj.roomDevice = obj.roomDevice.join('、');
                    if(obj.roomStatus == '已闲置'){
                        delete obj.oldmanName;
                        delete obj.oldmanCardId;
                        delete obj.oldmanId;
                    };

                    this.$api.updateRooms( obj ).then((res)=>{
                        if( this.form.id ){
                            this.$message.success("修改房间信息成功");
                        }else {
                            this.$message.success("新增房间信息成功");
                        };
                        this.editVisible = false;
                        this.handleSearch();
                    });

                });

            },

            /**
             * 分页导航 改变展示页
             */
            handlePageChange(val) {
                this.$set(this.query, 'currentPage', val);
                this.getData();
            },

            /**
             * 分页导航 改变展示数量
             * @param index
             */
            handleSizeChange(index) {
                this.$set(this.query, 'pageSize', index);
                this.getData();
            },

            /**
             * 加载页面基本数据
             */
            loadBasicData() {

                // 获取老人列表
                this.$api.getAllOlders().then((res)=>{
                    this.oldmanList = res.data;
                });

            },

        },
        beforeMount() {

            // 加载页面初始数据
            this.getData();
            this.loadBasicData();
        }
    };
</script>

<style lang="less">

</style>
